const fs = require('fs')
const { JWTgetInfo } = require(':JWT')
module.exports = app => {
  app.use(async (ctx, next) => {
    //如果是登录直接跳过
    if(ctx.originalUrl.indexOf("/user/getgitinfo")!==-1){
      await next()
      return
    }
    try {
      const { token = null } = ctx.request.header
      if(token==="getstart"){
        await next();
        return
      }
      ctx.state.userInfo = JWTgetInfo(token)
    } catch (err) {
      console.log(`报错文件：${__filename}`,err)
      ctx.throw(401)
    }
    await next()
  })
    // 同步读取文件夹
    fs.readdirSync(__dirname).forEach(file => {
        if (file === 'index.js') return
        const route = require(`./${file}`)
        app.use(route.routes()).use(route.allowedMethods())
    })

    app.use(async (ctx, next) => {
      try {
        if (ctx.status === 404) {
          // console.log(ctx.status)
          // ctx.throw(404)
          ctx.body = ctx.originalUrl
  
        }
      } catch (err) {
          console.log(321)
          // ctx.throw(404)
      }
      await next()
    })

}